package com.oceanstar.service.Impl;

import com.oceanstar.Pojo.*;
import com.oceanstar.mapper.ChaperonMapper;
import com.oceanstar.mapper.MallMapper;
import com.oceanstar.service.IMallService;
import com.oceanstar.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MallServiceImpl implements IMallService {
    // 注入mapper
    private final MallMapper mallMapper;
    // 构造器注入
    public MallServiceImpl(MallMapper mallMapper) {
        this.mallMapper = mallMapper;
    }

    /*
     *该接口用于管理员新增服务商城中的服务项目（如家政保洁、上门维修、陪护照护等）
     */
    @Override
    public void publicService(MallService service, String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        if (identity != 3 && identity != 4) {
            throw new Exception("需为管理员或网格员权限");
        }
        service.setCreateTime(new Date());
        service.setUpdateTime(service.getCreateTime());
        try {
            mallMapper.insertService(service);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }
    }

    /*
     *该接口用于管理员修改服务项目信息（名称、价格、描述、上架状态等）。
     */
    @Override
    public void updateService(MallService service, String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        if (identity != 3 && identity != 4) {
            throw new Exception("需为管理员或网格员权限");
        }
        if(service.getId() == null){
            throw new Exception("服务不存在");
        }
        MallService service1 = mallMapper.selectServiceById(service.getId());
        if (service1 == null) {
            throw new Exception("服务不存在");
        }
        if (service.getName() != null) {
            service1.setName(service.getName());
        }
        if (service.getCategory() != null) {
            service1.setCategory(service.getCategory());
        }
        if (service.getDescription() != null) {
            service1.setDescription(service.getDescription());
        }
        if (service.getPrice() != null) {
            service1.setPrice(service.getPrice());
        }
        if (service.getUnit() != null) {
            service1.setUnit(service.getUnit());
        }
        if (service.getServiceArea() != null) {
            service1.setServiceArea(service.getServiceArea());
        }
        if (service.getContactPhone() != null) {
            service1.setContactPhone(service.getContactPhone());
        }
        if (service.getStatus() != null) {
            service1.setStatus(service.getStatus());
        }
        service1.setUpdateTime(new Date());
        mallMapper.updateService(service1);
    }

    /*
     * 该接口用于管理员批量删除服务项目
     */
    @Override
    public void deleteServices(String ids, String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        if (identity != 3 && identity != 4) {
            throw new Exception("需为管理员或网格员权限");
        }

        // 验证参数
        if (ids == null || ids.trim().isEmpty()) {
            throw new Exception("参数ids不能为空");
        }

        // 解析ID列表
        String[] idArray = ids.split(",");
        List<Integer> idList = new ArrayList<>();

        for (String idStr : idArray) {
            try {
                Integer id = Integer.parseInt(idStr.trim());
                idList.add(id);
            } catch (NumberFormatException e) {
                throw new Exception("参数ids格式错误，应为数字用逗号分隔");
            }
        }

        if (idList.isEmpty()) {
            throw new Exception("未提供有效的服务ID");
        }

        mallMapper.deleteServicesByIds(idList);
    }

    @Override
    public PageInfo<MallService> getServiceList(String name, String category, Integer minPrice, Integer maxPrice, Integer status, Integer page, Integer pageSize, String token) throws Exception {
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            throw new Exception("token无效");
        }

        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        // 默认只查询上架的服务
        if (status == null) {
            status = 1;
        }
        // 价格区间验证
        if (minPrice != null && minPrice < 0) {
            throw new Exception("最低价格不能小于0");
        }
        if (maxPrice != null && maxPrice < 0) {
            throw new Exception("最高价格不能小于0");
        }
        if (minPrice != null && maxPrice != null && minPrice > maxPrice) {
            throw new Exception("最低价格不能大于最高价格");
        }
        try {
            Integer offset = (page - 1) * pageSize;

            // 查询数据
            List<MallService> services = mallMapper.selectServiceList(
                    name, category, minPrice, maxPrice, status, offset, pageSize);

            // 查询总数
            Long total = mallMapper.selectServiceCount(
                    name, category, minPrice, maxPrice, status);

            return new PageInfo<>(total, services);
        } catch (Exception e) {
            throw new Exception("查询服务列表失败: " + e.getMessage());
        }
    }

    /*
     * 该接口用于查询单个服务项目的详细信息
     */
    @Override
    public MallService getServiceDetail(Integer id, String token) throws Exception{
        // 验证token有效性
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            throw new Exception("token无效");
        }
        MallService service = mallMapper.selectServiceById(id);
        if (service == null) {
            throw new Exception("服务不存在");
        }
        try {
            return service;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    @Override
    public OrderSubmitResult submitOrder(OrderSubmitDTO orderDTO, String token) throws Exception {
        // 解析token获取用户信息
        Claims claims = JwtUtils.parseToken(token);
        Integer userId = (Integer) claims.get("id");
        String username = (String) claims.get("name");
        Integer identity = (Integer) claims.get("identity");

        // 验证用户身份（只能是老人或家属）
        if (identity != 1 && identity != 2) {
            throw new Exception("只有老人或家属可以下单");
        }
        // 验证服务是否存在且上架
        MallService service = mallMapper.selectServiceById(orderDTO.getServiceId());
        if (service == null) {
            throw new Exception("服务不存在");
        }
        if (service.getStatus() == 0) {
            throw new Exception("服务已下架");
        }
        // 验证服务日期不能是过去的时间
        LocalDate serviceDate = LocalDate.parse(orderDTO.getServiceDate());
        if (serviceDate.isBefore(LocalDate.now())){
            throw new Exception("服务日期不能是过去的时间");
        }
        String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 创建订单编号
        Integer todayCount = mallMapper.selectTodayOrderCount();
        String sequence = String.format("%03d", (todayCount == null ? 0 : todayCount) + 1);
        String orderId = "MALL" + dateStr + sequence;
        // 创建订单
        MallOrder order = new MallOrder();
        order.setOrderId(orderId);
        order.setServiceId(orderDTO.getServiceId());
        order.setServiceName(service.getName());
        order.setServiceCategory(service.getCategory());
        order.setPrice(service.getPrice());
        order.setUnit(service.getUnit());
        order.setServiceDate(orderDTO.getServiceDate());
        order.setTimeSlot(orderDTO.getTimeSlot());
        order.setAddress(orderDTO.getAddress());
        order.setContactName(orderDTO.getContactName());
        order.setContactPhone(orderDTO.getContactPhone());
        order.setRemark(orderDTO.getRemark());
        order.setUserId(userId);
        order.setUsername(username);
        order.setUserIdentity(identity);
        order.setStatus(1);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        mallMapper.insertOrder(order);

        //返回响应数据
        OrderSubmitResult result = new OrderSubmitResult();
        result.setOrderId(orderId);
        result.setCreateTime(order.getCreateTime());
        result.setStatus(order.getStatus());

        return result;
    }

    @Override
    public PageInfo<OrderVO> getMyOrders(Integer status, Integer page, Integer pageSize, String token) throws Exception {
        // 解析token获取用户信息
        Claims claims = JwtUtils.parseToken(token);
        Integer userId = (Integer) claims.get("id");
        Integer identity = (Integer) claims.get("identity");

        // 验证用户身份（只能是老人或家属）
        if (identity != 1 && identity != 2) {
            throw new Exception("只有老人或家属可以查看订单");
        }

        // 参数验证和默认值处理
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        Integer offset = (page - 1) * pageSize;

        // 查询订单列表
        List<OrderVO> orders = mallMapper.selectMyOrders(userId, status, offset, pageSize);

        // 查询订单总数
        Long total = mallMapper.selectMyOrdersCount(userId, status);

        return new PageInfo<>(total, orders);
    }

    @Override
    public void cancelOrder(String orderId, String token) throws Exception {
        // 解析token获取用户信息
        Claims claims = JwtUtils.parseToken(token);
        Integer userId = (Integer) claims.get("id");
        Integer identity = (Integer) claims.get("identity");

        // 验证用户身份（只能是老人或家属）
        if (identity != 1 && identity != 2) {
            throw new Exception("只有老人或家属可以取消订单");
        }

        // 参数验证
        if (orderId == null || orderId.trim().isEmpty()) {
            throw new Exception("订单编号不能为空");
        }

        try {
            // 查询订单信息
            MallOrder order = mallMapper.selectOrderByOrderId(orderId);
            if (order == null) {
                throw new Exception("订单不存在");
            }

            // 验证订单归属
            if (!order.getUserId().equals(userId)) {
                throw new Exception("只能取消自己的订单");
            }

            // 验证订单状态（只允许取消待接单、已接单的订单）
            if (order.getStatus() != 1 && order.getStatus() != 2) {
                throw new Exception("只能取消待接单或已接单的订单");
            }

            // 更新订单状态为已取消
            mallMapper.updateOrderStatus(orderId, 5, new Date());

        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    @Override
    public PageInfo<MallOrder> getAdminOrders(String orderId, String serviceName, Integer status, String beginDate, String endDate, String elderName, String contactPhone, Integer page, Integer pageSize, String token) throws Exception {
        // 解析token验证管理员权限
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        if (identity != 3 && identity != 4) {
            throw new Exception("需为管理员或网格员权限");
        }

        // 参数验证和默认值处理
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        if (beginDate != null && endDate != null && beginDate.compareTo(endDate) > 0) {
            throw new Exception("开始日期不能大于结束日期");
        }
        Integer offset = (page - 1) * pageSize;

        // 查询订单列表
        List<MallOrder> orders = mallMapper.selectAdminOrders(
                orderId, serviceName, status, beginDate, endDate, elderName, contactPhone, offset, pageSize);

        // 查询订单总数
        Long total = mallMapper.selectAdminOrdersCount(
                orderId, serviceName, status, beginDate, endDate, elderName, contactPhone);

        return new PageInfo<>(total, orders);
    }

    @Override
    public void handleOrder(OrderHandleDTO handleDTO, String token) throws Exception {
        // 解析token验证管理员权限
        Claims claims = JwtUtils.parseToken(token);
        Integer operatorId = (Integer) claims.get("id");
        String operatorName = (String) claims.get("name");
        Integer identity = (Integer) claims.get("identity");

        if (identity != 3 && identity != 4) {
            throw new Exception("需为管理员或网格员权限");
        }

        // 参数验证
        if (handleDTO.getOrderId() == null || handleDTO.getOrderId().trim().isEmpty()) {
            throw new Exception("订单编号不能为空");
        }
        if (handleDTO.getStatus() == null || handleDTO.getStatus() < 2 || handleDTO.getStatus() > 5) {
            throw new Exception("目标状态值无效");
        }

        // 查询订单信息
        MallOrder order = mallMapper.selectOrderByOrderId(handleDTO.getOrderId());
        if (order == null) {
            throw new Exception("订单不存在");
        }

        // 记录操作前的状态
        Integer fromStatus = order.getStatus();

        // 验证状态流转是否合法
        validateStatusTransition(order.getStatus(), handleDTO.getStatus());

        // 更新订单状态
        mallMapper.updateOrderStatusAndRemark(
                handleDTO.getOrderId(),
                handleDTO.getStatus(),
                new Date()
        );

        // 记录操作日志
        OrderOperationLog log = new OrderOperationLog();
        log.setOrderId(handleDTO.getOrderId());
        log.setFromStatus(fromStatus);
        log.setToStatus(handleDTO.getStatus());
        log.setHandleRemark(handleDTO.getHandleRemark());
        log.setOperatorId(operatorId);
        log.setOperatorName(operatorName);
        log.setCreateTime(new Date());
        log.setUpdateTime(new Date());

        mallMapper.insertOperationLog(log);
    }
    /**
     * 验证状态流转是否合法
     */
    private void validateStatusTransition(Integer currentStatus, Integer targetStatus) throws Exception {
        // 状态流转规则：
        // 1(待接单) -> 2(已接单), 5(取消)
        // 2(已接单) -> 3(进行中), 5(取消)
        // 3(进行中) -> 4(完成), 5(取消)
        // 4(完成) -> 不允许再修改
        // 5(取消) -> 不允许再修改

        if (currentStatus == 4 || currentStatus == 5) {
            throw new Exception("已完成或已取消的订单不允许修改状态");
        }

        switch (currentStatus) {
            case 1: // 待接单
                if (targetStatus != 2 && targetStatus != 5) {
                    throw new Exception("待接单订单只能接单或取消");
                }
                break;
            case 2: // 已接单
                if (targetStatus != 3 && targetStatus != 5) {
                    throw new Exception("已接单订单只能标记为进行中或取消");
                }
                break;
            case 3: // 进行中
                if (targetStatus != 4 && targetStatus != 5) {
                    throw new Exception("进行中订单只能标记为完成或取消");
                }
                break;
            default:
                throw new Exception("当前订单状态不支持此操作");
        }
    }


}
